package com.pine.sunshineelder.login.web.filter;

import java.io.IOException;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(urlPatterns = "/view/*", dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD })
public class LoginFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 1转换为httpServletXXX
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String origin = req.getHeader("Origin");
		resp.setHeader("Access-Control-Allow-Origin", origin);
		resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		resp.setHeader("Access-Control-Max-Age", "3600");
		resp.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
		resp.setHeader("Access-Control-Allow-Credentials", "true");
		String method = req.getMethod();
		if (method.equalsIgnoreCase("OPTIONS")) {
			response.getOutputStream().write("Success".getBytes("utf-8"));
		} else {

			// 把请求传递到下一个节点(下一个过滤器或servlet)
			chain.doFilter(req, resp);
		}
	}

	private boolean isLogin(HttpServletRequest req) {
		return req.getSession().getAttribute("currentUser") != null;
	}
}
